package com.bankcomm.util;

import com.bankcomm.audio.AudioServerManager;
import com.bankcomm.audio.EventHandler;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.ui.EMPView;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.WaitProgressDialog;
import com.rytong.tools.utils.Utils;

import excelsecu.mobile.usbkey.ESMobileImpl;
import ftsafe.mobile.usbkey.FTMobileImpl;
import bocom.mobile.usbkey.IMobile;
import bocom.mobile.usbkey.IMobile.DeviceInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;

/**
 * BOCMobile.java
 * 
 * @author sun_t
 */

public class BOCKeyMobile {
	private final int OPERATE_FAIL = 0;// 失败
	private final int CONNECT_SUCCESS = 1;// 设备连接成功
	private final int SIGN_SUCCESS = 2;// 签名成功
	private final int GET_CERTS_SCUCCESS = 3;// 获取证书列表成功
	private final int GET_BUILD55FIELD_SCUCCESS = 5;// 获取55域成功
	private final int GET_EXECSCRIPT_SCUCCESS = 6;// 验证后台响应报文成功
	private final int GET_CARDINFO_SCUCCESS = 7;// 验证后台响应报文成功

	private final String noConnect = "当前未连接,请将Key插入音频口之后再试！";
	private final String connecting = "注意，请在您插入的key上面输入key的密码，交易中请勿断开";

	// IMobile接口
	private IMobile iMobile = null;

	// 证书列表
	private String[] certs;
	private String noSignData;

	private EMPView bv_;
	
	private AlertDialog alert_;
	
	public String signResult = null;
	private Component component = null;
	
	// 是否激活验证
	private static final int FTActivation = 0x6001000F;
	private static final int ESActivation = 0x60606003;
	private static final int TDRActivation = 0x0000000E;
	
	AudioServerManager asm_;
	
	public BOCKeyMobile(Context context) {
		this.bv_ = (EMPView) context;
		
		newHandler();
	}
	
	public IMobile getIMobile(){
		return iMobile;
	}
	Handler mHandler ;
	public  void newHandler(){
	mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case OPERATE_FAIL:
				// 关闭提示信息
				if (alert_ != null) {
					alert_.dismiss();
				}
				if (null != msg.obj) {
					alert(String.valueOf(msg.obj));
				}
				// 如果openDevice失败、获取证书失败或签名失败都调用closeDevice()方法
				closeDevice();
				break;
			case CONNECT_SUCCESS:
				if (null != msg.obj) {
					alert(String.valueOf(msg.obj));
				}
				getCertsList();// 连接成功后获取证书
				break;
			case GET_CERTS_SCUCCESS:
				selectCert();// 获取证书成功后签名
				break;
			case SIGN_SUCCESS:
				// 关闭提示信息
				if (alert_ != null) {
					alert_.dismiss();
				}
				
				if (null != component && null != msg.obj) {
					String result = String.valueOf(msg.obj);
					if(null != result && !"".equalsIgnoreCase(result)){
						signResult = result;
						Utils.printOutToConsole("--------------  >>>" + result);
						bv_.sendForm(component.findparentForm(component));						
					}
				}
				
				// 如果签名成功调用closeDevice()方法
				closeDevice();
				break;
			}
			super.handleMessage(msg);
		}
	};
	}
	
	public void open(final String data){
		this.signResult = data;
		asm_ = new AudioServerManager(bv_, this);
	}
	
	
	/**
	 * 通过枚举，找到当前连接设备是哪个厂商
	 * */
	public void openDevice(final String data) {
		
		new Task() {

			@Override
			void taskBody() {
				/* openDevices ----  start */
				noSignData = data;
				
				for (int i = 1; i < 3; i++) { //天地融的不用了（卫老师说的20140210）
					if (i == 0) {
						//  天地融
//						tendyron.akey.ibank.impl.TDRMobileImpl tdrMobile = new tendyron.akey.ibank.impl.TDRMobileImpl();
//						tdrMobile.Init(bv_);
//						DeviceInfo deviceInfo = tdrMobile.OpenDevice();
//						System.out.println(tdrMobile.IsConnect());
//						if (deviceInfo != null && tdrMobile.IsConnect()) {
//							iMobile = tdrMobile;
//							break;
//						} else {
//							tdrMobile.CloseDevice();
//							tdrMobile = null;
//						}
					} else if (i == 1) {
						// FTMobile
						FTMobileImpl ftMobile = new FTMobileImpl();
						ftMobile.Init(bv_);
						DeviceInfo ftInfo = ftMobile.OpenDevice();
						System.out.println(ftMobile.IsConnect());
						if(null != ftInfo && ftMobile.IsConnect()){
							iMobile = ftMobile;
							break;
						}else{
							ftMobile.CloseDevice();
							ftMobile = null;
						}
					} else if (i == 2){
						// ESMobile
						ESMobileImpl wtMobile = new ESMobileImpl();
						wtMobile.Init(bv_);
						DeviceInfo deviceInfo = wtMobile.OpenDevice();
						System.out.println(wtMobile.IsConnect());
						if (deviceInfo != null && wtMobile.IsConnect()) {
							iMobile = wtMobile;
							break;
						}else{
							wtMobile.CloseDevice();
							wtMobile = null;
						}
					}
				}
				if (null != iMobile && iMobile.IsConnect()) {
					mHandler.sendMessage(mHandler.obtainMessage(
							CONNECT_SUCCESS, connecting));
				} else {
					mHandler.sendMessage(mHandler.obtainMessage(OPERATE_FAIL,
							noConnect));
				}
				
				/* openDevices ----  end */
			}
			
		}.start();
	}
	
	/**
	 * 
	 * @param com
	 */
	public void setComponent(Component com){
		this.component = com;
	}
	
	/**
	 * 获取证书列表
	 */
	public void getCertsList() {
		new Task() {
			
			@Override
			void taskBody() {

				if (null != iMobile && iMobile.IsConnect()) {
					certs = iMobile.GetCertList();
					if (certs != null && certs.length > 0) {
						mHandler.sendMessage(mHandler.obtainMessage(
								GET_CERTS_SCUCCESS, null));
					} else {
						mHandler.sendMessage(mHandler.obtainMessage(
								OPERATE_FAIL,
								"获取证书列表失败:" + iMobile.GetErrCode()));
					}
				} else {
					mHandler.sendMessage(mHandler.obtainMessage(OPERATE_FAIL,
							noConnect));
				}

			}
		}.start();
	}
	
	/**
	 * 签名
	 */
	public void signWithCert(final String certKey) {
		
		new Task() {
			
			@Override
			void taskBody() {
				if (iMobile != null && iMobile.IsConnect()) {
					int hashType = IMobile.HASH_SHA160;
					String signResult = iMobile.CertSign(hashType,certKey,IMobile.ENCODE_UTF_8, noSignData);
					System.out.println("签名后---   >>>" + signResult);
					// 判断智慧网盾是否激活
					if (iMobile.GetErrCode() != ESActivation && iMobile.GetErrCode() != FTActivation
							&& iMobile.GetErrCode() != TDRActivation) {
						if (null != signResult) {
							mHandler.sendMessage(mHandler.obtainMessage(
									SIGN_SUCCESS, signResult));
						} else {
							mHandler.sendMessage(mHandler.obtainMessage(
									OPERATE_FAIL, "签名失败:" + iMobile.GetErrCode()));
						}
					} else {
						if (alert_ != null) {
							alert_.dismiss();
							closeDevice();
						}
					}
				} else {
					mHandler.sendMessage(mHandler.obtainMessage(OPERATE_FAIL,
							noConnect));
				}
			}
		}.start();
		
	}
	
	/**
	 * 组织55域报文
	 * @param sTransAmount:	圈存金额，长度为12;
	 * @return:
	 * 	成功：PAN|返回55域报文;
	 * 	失败：2个字节的错误码;
	 */
//	public void Build55Field(final String sTransAmount) {
//		new Task() {
//			
//			@Override
//			void taskBody() {
//				if (iMobile != null && iMobile.IsConnect()) {
//					String result = iMobile.Build55Field(sTransAmount);
//					System.out.println("55域报文------>>>>>" + result);
//					if (result != null && !result.equals("")) {
//						mHandler.sendMessage(mHandler.obtainMessage(
//								GET_BUILD55FIELD_SCUCCESS, result));
//					} else {
//						mHandler.sendMessage(mHandler.obtainMessage(
//								OPERATE_FAIL, "55域返回失败:" + iMobile.GetErrCode()));
//					}
//				} else {
//					mHandler.sendMessage(mHandler.obtainMessage(OPERATE_FAIL,
//							noConnect));
//				}
//			}
//		}.runTask();
//	}
	
	/**
	 * 验证后台响应报文，并执行脚本
	 * @sPutDataString:	后台响应报文
	 * return:
	 * 成功：返回0；
	 * 失败：返回错误码;
	 */
//	public void ExecScript(final String sPutDataString){
//		new Task() {
//			
//			@Override
//			void taskBody() {
//				if (iMobile != null && iMobile.IsConnect()) {
//					int result = iMobile.ExecScript(sPutDataString);
//					System.out.println("验证后台响应报文------>>>>>" + result);
//					if (result == 0) {
//						mHandler.sendMessage(mHandler.obtainMessage(
//								GET_EXECSCRIPT_SCUCCESS, result));
//					} else {
//						mHandler.sendMessage(mHandler.obtainMessage(
//								OPERATE_FAIL, "验证后台失败:" + iMobile.GetErrCode()));
//					}
//				} else {
//					mHandler.sendMessage(mHandler.obtainMessage(OPERATE_FAIL,
//							noConnect));
//				}
//			}
//		}.runTask();
//	}
	
	/**
	 * 获取卡片数据，包括PAN、电子现金余额
	 * return:
	 * 成功：返回PAN、电子现金余额，以"|"分割；
	 * 失败：返回长度2的错误码;
	 */
	public void GetCardInfo(){
//		return null;
	}
	
	/**
	 * 关闭设备
	 */
	public void closeDevice() {
		if (null != iMobile) {
			if (AudioServerManager.isAudioAdapterConnect) {
				Message m = new Message();
				m.what = 1006;
				Handler handler = EventHandler.ut.eventHandler;
				handler.sendMessage(m);
				AudioServerManager.isAudioAdapterConnect = false;
			}
			iMobile.CloseDevice();
			if (asm_ != null) {
				asm_ = null;
			}
		}
	}

	/**
	 * 证书列表，选择证书
	 * */
	public void selectCert() {
//		new AlertDialog.Builder(bv).setTitle("选择签名证书")
//				.setItems(certs, new DialogInterface.OnClickListener() {
//
//					@Override
//					public void onClick(DialogInterface arg0, int index) {
						signWithCert(certs[0]);
//					}
//				}).show();
	}

	/**
	 * 提示信息对话框
	 * */
	public void alert(String msg) {
		alert_ = new AlertDialog.Builder(bv_).setTitle("提示").setMessage(msg)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						
					}
				}).show();
	}
	
	abstract class Task extends Thread {
		
		@Override
		public void run() {
			showDialog();
			
			try {
				taskBody();
			} finally {
				closeDialog();
			}
			
		}
		
		abstract void taskBody();
		
		private void closeDialog() {
			mHandler.post(new Runnable() {

				@Override
				public void run() {
					if (bv_.waitProgress != null && bv_.waitProgress.isShowing()) {
						bv_.waitProgress.dismiss();
					}
				}
			});
		}

		private void showDialog() {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					if (bv_.waitProgress == null) {
						bv_.waitProgress = new WaitProgressDialog(ConfigManager.currentView_);
					}
					if (!bv_.waitProgress.isShowing()) {
						bv_.waitProgress.show(null, true);
					}
				}
			});
		}
	} 
}
